﻿using System;
using System.IO;
using GeoAPI.Geometries;

namespace YJKGridTopologyCal.Noding
{
	public class SegmentNode : IComparable
	{
		public SegmentNode(INodableSegmentString segString, Coordinate coord, int segmentIndex, Octants segmentOctant)
		{
			this.Coord = null;
			this._segString = segString;
			this.Coord = new Coordinate(coord.X, coord.Y, coord.Z);
			this.SegmentIndex = segmentIndex;
			this._segmentOctant = segmentOctant;
			this._isInterior = !coord.Equals2D(segString.Coordinates[segmentIndex]);
		}

		public Coordinate Coordinate
		{
			get
			{
				return this.Coord;
			}
		}

		public bool IsInterior
		{
			get
			{
				return this._isInterior;
			}
		}

		public bool IsEndPoint(int maxSegmentIndex)
		{
			return (this.SegmentIndex == 0 && !this._isInterior) || this.SegmentIndex == maxSegmentIndex;
		}

		public int CompareTo(object obj)
		{
			SegmentNode segmentNode = (SegmentNode)obj;
			if (this.SegmentIndex < segmentNode.SegmentIndex)
			{
				return -1;
			}
			if (this.SegmentIndex > segmentNode.SegmentIndex)
			{
				return 1;
			}
			if (this.Coord.Equals2D(segmentNode.Coord))
			{
				return 0;
			}
			return SegmentPointComparator.Compare(this._segmentOctant, this.Coord, segmentNode.Coord);
		}

		public void Write(StreamWriter outstream)
		{
			outstream.Write(this.Coord);
			outstream.Write(" seg # = " + this.SegmentIndex);
		}

		public readonly Coordinate Coord;

		public readonly int SegmentIndex;

		private readonly INodableSegmentString _segString;

		private readonly Octants _segmentOctant = Octants.Null;

		private readonly bool _isInterior;
	}
}
